//
//  MCUserinfoViewController.swift
//  WisdomSpace
//
//  Created by goulela on 2017/9/4.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCUserinfoViewController: MCViewController {

    fileprivate let dataArray = ["头像","昵称","手机号","身份","修改登录密码"]
    fileprivate var nickName : String?
    public var dataDict : [String:Any]?

    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        sendNetworking()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        manageClosure()
    }
    
    // MARK: - Network
    func sendNetworking() {

        let para = [
            "baUserId" : MCUserinfo_getUserId(),
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_getStoreUserByIdAndStoreId, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            let dataDict = response["data"] as! [String : AnyObject]
            let userName = dataDict["userName"] as? String ?? ""
            let nickName = dataDict["nickName"] as? String ?? ""
            let picture = dataDict["picture"] as? String ?? ""
            let levelTemp = dataDict["level"] as? NSNumber ?? 0
            let levelTuples = MCLevelConversion(level: levelTemp.intValue)
            
            self.iconImageView.sd_setImage(with: URL.init(string: picture), placeholderImage: #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
            self.nickNameLabel.text = nickName
            self.phoneLabel.text = userName
            self.identityLabel.text = levelTuples.levelName
            
            UserDefaults.LoginInfo.set(value: nickName, forKey: .nickName)
            UserDefaults.LoginInfo.set(value: picture, forKey: .picture)
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    func sendNetworking_modifyIcon(image : UIImage) {
        
        let imageData = UIImageJPEGRepresentation(image, 0.1)
        let base = imageData?.base64EncodedString() ?? ""
    
        let para = [
            "imgBase" : base,
            "suffix"  : "png"
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_alterUserPicture, para: para as [String : AnyObject], vc: self, hudSuperView: nil, isHiddenTabbar: false, success: { (response) in
            
            self.iconImageView.image = image
            self.tableView.reloadData()
            
        }, dislike: { (response) in }) { (error) in }
    }
    
    
    
    // MARK: - Closure
    func manageClosure() {
        
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "个人信息"
        self.view.backgroundColor = UIColor.MCGray_light
    }
    
    func initUI() {
        
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) -> Void in
            make.left.right.top.equalTo(view)
            make.height.equalTo(dataArray.count * 50 + 30)
        }
    }
    
    
    
    // 图库
    func libraryClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let vc = UIImagePickerController()
            vc.navigationBar.isTranslucent = false
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = UIImagePickerControllerSourceType.photoLibrary
            self.present(vc, animated: true, completion: { })
        }
    }
    
    // 拍照
    func cameraClicked() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            
            let availableMeidatypes : NSArray = UIImagePickerController.availableMediaTypes(for: UIImagePickerControllerSourceType.camera)! as NSArray
            
            var canTakePicture = false
            
            for mediaType in availableMeidatypes {
                
                let str = mediaType as? String
                
                if str == String(kUTTypeImage) {
                    canTakePicture = true
                    break
                }
            }
            
            guard canTakePicture else {
                return
            }
            
            let vc = UIImagePickerController()
            vc.delegate = self
            vc.allowsEditing = true
            vc.sourceType = UIImagePickerControllerSourceType.camera
            vc.mediaTypes = NSArray(object: String(kUTTypeImage)) as! [String]
            self.present(vc, animated: true, completion: { })
            
        }
    }

    
    // MARK: - Setter & Getter
    fileprivate lazy var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = UIColor.MCGray_light
        tableView.isScrollEnabled = false
        return tableView
    }()
    
   fileprivate lazy var iconImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.layer.cornerRadius = 25
        imageView.layer.masksToBounds = true
        imageView.layer.borderColor = UIColor.MCGray_light.cgColor
        imageView.layer.borderWidth = 1
        imageView.image = #imageLiteral(resourceName: "Reuse_icon")
        
        return imageView
    }()
    
    fileprivate lazy var nickNameLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.textColor = UIColor.MCGray_middle
        return label
    }()
    
    fileprivate lazy var identityLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.text = "分销员"
        label.textColor = UIColor.MCGray_middle
        return label
    }()

    
    fileprivate lazy var phoneLabel: UILabel = {
        let label = UILabel()
        label.font = MCFont(14)
        label.textColor = UIColor.MCGray_middle
        return label
    }()
    

}



extension MCUserinfoViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.item {
        case 0:
            return 80
        default:
            return 50
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = UITableViewCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.backgroundColor = UIColor.white
        
        cell.textLabel?.font = MCFont(14)
        cell.textLabel?.text = dataArray[indexPath.row]
        cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator

        
        
        if indexPath.row != (self.dataArray.count - 1) {
            let line = UIView()
            line.backgroundColor = UIColor.MCGray_light
            cell.addSubview(line)
            line.snp.remakeConstraints { (make) -> Void in
                make.right.bottom.equalTo(cell)
                make.left.equalTo(cell).offset(0)
                make.height.equalTo(1)
            }
        }
        
        if indexPath.row == 0 {
            cell.contentView.addSubview(iconImageView)
            iconImageView.snp.remakeConstraints { (make) -> Void in
                make.centerY.equalTo(cell.contentView)
                make.right.equalTo(0)
                make.size.equalTo(CGSize.init(width: 50, height: 50))
            }
        }
        
        if indexPath.row == 1 {
            cell.contentView.addSubview(nickNameLabel)
            nickNameLabel.snp.remakeConstraints { (make) -> Void in
                make.centerY.equalTo(cell.contentView)
                make.right.equalTo(0)
            }
        }
      
        if indexPath.row == 2 {
            cell.accessoryType = UITableViewCellAccessoryType.none
            cell.contentView.addSubview(phoneLabel)
            phoneLabel.snp.remakeConstraints { (make) -> Void in
                make.centerY.equalTo(cell.contentView)
                make.right.equalTo(-31)
            }
        }
        
        if indexPath.row == 3 {
            cell.accessoryType = UITableViewCellAccessoryType.none
            cell.contentView.addSubview(identityLabel)
            identityLabel.snp.remakeConstraints { (make) -> Void in
                make.centerY.equalTo(cell.contentView)
                make.right.equalTo(-31)
            }

        }
        
        
        return cell
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
        case 0:
            let alterController = UIAlertController.init(title: "修改头像", message: nil, preferredStyle: UIAlertControllerStyle.actionSheet);
            let cancelAction = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
            })
            let libraryAction = UIAlertAction.init(title: "图库", style: UIAlertActionStyle.default, handler: { (action) in
                self.libraryClicked()
            })
            
            let cameraAction = UIAlertAction.init(title: "拍照", style: UIAlertActionStyle.default, handler: { (action) in
                self.cameraClicked()
            })
            
            alterController.addAction(cancelAction)
            alterController.addAction(libraryAction)
            alterController.addAction(cameraAction)
            
            self.present(alterController, animated: true, completion: {});
        case 1:
            let vc = MCModifyNickNameViewController()
            vc.name = self.nickName
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        case 4:
            let vc = MCChangePasswordOneViewController()
            vc.phoneNumber = self.phoneLabel.text ?? ""
            vc.fatherVC = self
            MCPushToViewController(current: self, target: vc, isHiddenBottomBarWhenBack: true)
        default:
            break
        }
    }
}

extension MCUserinfoViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let mediaType = info[UIImagePickerControllerMediaType] as! String
        
        if mediaType == String(kUTTypeImage) {
            
            let originalImage : UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage
            
            let rect = info[UIImagePickerControllerCropRect] as! CGRect
    
            let editedImage = originalImage.MCImageCrop(toRect: rect)

            iconImageView.image = editedImage
            sendNetworking_modifyIcon(image: editedImage)

            picker.dismiss(animated: true, completion: nil)
        }
    }
}



